/**
 * @Author: yqe@360shop.cn
 * @Date: 2019-09-26 16:48:09
 * @Last Modified by: zhangmeng
 * @Last Modified time: 2020-07-02 23:43:10
 */
import Store from '@/utils/store'
import router from '../router'
import store from '../store'

/**
 * 路由跳转
 */
export function routeTo(sid, pid) {
  const localQuery = Store.fetchLocal('query')
  let newQuery = ''
  for (const key in localQuery) {
    if (!(key == 'sid' || key == 'pid')) {
      newQuery += key + '=' + localQuery[key] + '&'
    }
  }
  let url = ''
  newQuery = newQuery.substr(0, newQuery.length - 1)
  // const detailId = Store.fetchLocal('detailId')
  const localSid = Store.fetchLocal('sid')
  const host = window.location.host
  const href = window.location.href
  const http = href.substring(0, 5) === 'https' ? 'https://' : 'http://'
  // const url = `${http}${host}${router.currentRoute.path}?sid=${sid || localSid}&pid=${pid}&detailId=${detailId}`
  url = `${http}${host}${router.currentRoute.path}?sid=${sid || localSid}&pid=${pid}&${newQuery}`
  // // console.log(router)
  // // console.log(http)
  // // console.log(host)
  // // console.log(router.currentRoute.path)
  // console.log(url, '跳转链接')
  location.href = url
}

/**
 * 商品的价格处理 整数位放大
 * @price: 价格
 * @classNum: 自定义class
 */
export function scaleGoodsPrice(price, className, isCoupon) {
  const mSymbol = store.state.mSymbol.MoneySymbol.name
  if (!price) price = '0.00'
  const priceInt = parseInt(price)
  const priceFloat = parseFloat(price - priceInt).toFixed(2)
  const priceBack = priceFloat.slice(2)
  let priceStr = ''
  // 四位数以上的优惠券，不展示小数位
  const couponBig = (isCoupon == 1 && price - 1000 >= 0) ? 1 : 0
  // 两位数的优惠券，整数位字体放大
  const couponTiny = (isCoupon == 1 && price - 100 < 0) ? 1 : 0
  if (couponBig) {
    priceStr = `<div class='price-scale fontAliBaba ${className || ''}'><span class='unit'>${mSymbol}</span><span class='num-font'>${priceInt}</span></div>`
  } else if (couponTiny) {
    // console.log(222)
    priceStr = `<div class='price-scale fontAliBaba ${className || ''}'><span class='unit'>${mSymbol}</span><span class='num-font large'>${priceInt}.</span><span class='num-back'>${priceBack}</span></div>`
  } else {
    priceStr = `<div class='price-scale fontAliBaba ${className || ''}'><span class='unit'>${mSymbol}</span><span class='num-font'>${priceInt}.</span><span class='num-back'>${priceBack}</span></div>`
  }
  return priceStr
}
// 不带￥符号
export function scaleGoodsPriceNoMark(price, className) {
  if (!price) price = '0.00'
  const priceInt = parseInt(price)
  const priceFloat = parseFloat(price - priceInt).toFixed(2)
  const priceBack = priceFloat.slice(2)
  const priceStr = `<div class="price-scale ${className || ''}"><span class="num-font">${priceInt}.</span><span class="num-back">${priceBack}</span></div>`
  return priceStr
}

// 超出4个字符显示3个文字加省略号
export function getTitle(title) {
  let tempTitle = ''
  if (title.length > 4) {
    tempTitle = title.substring(0, 3) + '...'
  } else {
    tempTitle = title
  }
  return tempTitle
}

export function parseTime(time, cFormat) {
  if (arguments.length === 0) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if (('' + time).length === 10) time = parseInt(time) * 1000
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    if (key === 'a') return ['一', '二', '三', '四', '五', '六', '日'][value - 1]
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}

// 将时间戳转换为时间
export function formatDate(timestamp) {
  const date = new Date(timestamp * 1000) // 时间戳为10位需*1000，时间戳为13位的话不需乘1000
  const Y = date.getFullYear() + '-'
  const M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
  const D = date.getDate() < 10 ? '0' + date.getDate() + ' ' : date.getDate() + ' '
  const h = date.getHours() < 10 ? '0' + date.getHours() + ':' : date.getHours() + ':'
  const m = date.getMinutes() < 10 ? '0' + date.getMinutes() + ':' : date.getMinutes() + ':'
  const s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
  return Y + M + D + h + m + s
}

export function formatTime(time, option) {
  time = +time * 1000
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) { // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return d.getMonth() + 1 + '月' + d.getDate() + '日' + d.getHours() + '时' + d.getMinutes() + '分'
  }
}

export function formatDay(timestamp, type) {
  timestamp = timestamp.length == 10 ? timestamp * 1000 : timestamp
  const date = new Date(timestamp) // 时间戳为10位需*1000，时间戳为13位的话不需乘1000
  const Y = date.getFullYear() + '-'
  const M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
  const D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
  // 只返回日期不返回年
  if (type == 'M') {
    return M + D
  } else {
    return Y + M + D
  }
}
// 默认返回时分秒  第二个参数传'm' 返回小时和分钟
export function formatHMS(timestamp, type) {
  timestamp = timestamp.length == 10 ? timestamp * 1000 : timestamp
  const date = new Date(timestamp) // 时间戳为10位需*1000，时间戳为13位的话不需乘1000
  const h = date.getHours() < 10 ? '0' + date.getHours() + '' : date.getHours()
  const m = date.getMinutes() < 10 ? ':0' + date.getMinutes() : ':' + date.getMinutes()
  const s = date.getSeconds() < 10 ? ':0' + date.getSeconds() : ':' + date.getSeconds()
  if (type == 'm') {
    return h + m
  } else {
    return h + m + s
  }
}
/**
 *get getByteLen
 * @param {Sting} val input value
 * @returns {number} output value
 */
export function getByteLen(val) {
  let len = 0
  for (let i = 0; i < val.length; i++) {
    if (val[i].match(/[^\x00-\xff]/ig) != null) {
      len += 1
    } else { len += 0.5 }
  }
  return Math.floor(len)
}

export function cleanArray(actual) {
  const newArray = []
  for (let i = 0; i < actual.length; i++) {
    if (actual[i]) {
      newArray.push(actual[i])
    }
  }
  return newArray
}

export function getHtml(desc) {
  var temp = document.createElement('div')
  temp.innerHTML = desc
  var output = temp.innerText || temp.textContent
  temp = null
  return output
}

export function objectMerge(target, source) {
  /* Merges two  objects,
     giving the last one precedence */

  if (typeof target !== 'object') {
    target = {}
  }
  if (Array.isArray(source)) {
    return source.slice()
  }
  Object.keys(source).forEach((property) => {
    const sourceProperty = source[property]
    if (typeof sourceProperty === 'object') {
      target[property] = objectMerge(target[property], sourceProperty)
    } else {
      target[property] = sourceProperty
    }
  })
  return target
}

export function scrollTo(element, to, duration) {
  if (duration <= 0) return
  const difference = to - element.scrollTop
  const perTick = difference / duration * 10
  setTimeout(() => {
    // console.log(new Date())
    element.scrollTop = element.scrollTop + perTick
    if (element.scrollTop === to) return
    scrollTo(element, to, duration - 10)
  }, 10)
}

export function getTime(type) {
  if (type === 'start') {
    return new Date().getTime() - 3600 * 1000 * 24 * 90
  } else {
    return new Date(new Date().toDateString())
  }
}

export function debounce(func, wait, immediate) {
  let timeout, args, context, timestamp, result

  const later = function() {
    // 据上一次触发时间间隔
    const last = +new Date() - timestamp

    // 上次被包装函数被调用时间间隔last小于设定时间间隔wait
    if (last < wait && last > 0) {
      timeout = setTimeout(later, wait - last)
    } else {
      timeout = null
      // 如果设定为immediate===true，因为开始边界已经调用过了此处无需调用
      if (!immediate) {
        result = func.apply(context, args)
        if (!timeout) context = args = null
      }
    }
  }

  return function(...args) {
    context = this
    timestamp = +new Date()
    const callNow = immediate && !timeout
    // 如果延时不存在，重新设定延时
    if (!timeout) timeout = setTimeout(later, wait)
    if (callNow) {
      result = func.apply(context, args)
      context = args = null
    }

    return result
  }
}

export function deepClone(source) {
  if (!source && typeof source !== 'object') {
    throw new Error('error arguments', 'shallowClone')
  }
  const targetObj = source.constructor === Array ? [] : {}
  Object.keys(source).forEach((keys) => {
    if (source[keys] && typeof source[keys] === 'object') {
      targetObj[keys] = source[keys].constructor === Array ? [] : {}
      targetObj[keys] = deepClone(source[keys])
    } else {
      targetObj[keys] = source[keys]
    }
  })
  return targetObj
}
export function base64_encode(str) {
  let c1,
    c2,
    c3
  const base64EncodeChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
  let i = 0,
    len = str.length,
    string = ''

  while (i < len) {
    c1 = str.charCodeAt(i++) & 0xff
    if (i == len) {
      string += base64EncodeChars.charAt(c1 >> 2)
      string += base64EncodeChars.charAt((c1 & 0x3) << 4)
      string += '=='
      break
    }
    c2 = str.charCodeAt(i++)
    if (i == len) {
      string += base64EncodeChars.charAt(c1 >> 2)
      string += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4))
      string += base64EncodeChars.charAt((c2 & 0xF) << 2)
      string += '='
      break
    }
    c3 = str.charCodeAt(i++)
    string += base64EncodeChars.charAt(c1 >> 2)
    string += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4))
    string += base64EncodeChars.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >> 6))
    string += base64EncodeChars.charAt(c3 & 0x3F)
  }
  return string
}

export function getQueryParams(url) {
  // TODO 获取url中"?"符后的字串
  if (typeof url === 'string') {
    const theRequest = {}
    if (url.indexOf('?') != -1) {
      const str = url.split('?')[1]
      const strs = str.split('&')
      for (let i = 0; i < strs.length; i++) {
        theRequest[strs[i].split('=')[0]] = unescape(strs[i].split('=')[1]) || 0
      }
    }
    return theRequest
  }
}